from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, QueryDict
from utils.auth import login_required, conn_k8s_api
from utils.dateformat import dt_format
from kubernetes import client
import time


# Create your views here.


@login_required
def configmap(request):
    return render(request, "storage/configmap.html")


@login_required
def cm_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    namespace_val = request.GET.get("namespace")
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        cm_list = []
        try:
            for cm in core_api.list_namespaced_config_map(namespace_val).items:
                name = cm.metadata.name
                namespace = cm.metadata.namespace
                data_length = ("0" if cm.data is None else len(cm.data))
                create_time = cm.metadata.creation_timestamp
                create_time = dt_format(create_time)
                cm = {"name": name, "namespace": namespace, "data_length": data_length, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        cm_list.append(cm)
                else:
                    cm_list.append(cm)
            count = len(cm_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            cm_list = cm_list[start:end]
            code = 0
            msg = "configmap获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": cm_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            namespace = del_data.get('namespace')
            core_api.delete_namespaced_config_map(namespace=namespace, name=name)
            while True:
                name_list = []
                for cm in core_api.list_namespaced_config_map(namespace).items:
                    name_list.append(cm.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)


@login_required
def secret(request):
    return render(request, "storage/secret.html")


@login_required
def secret_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    namespace_val = request.GET.get("namespace")
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        secret_list = []
        try:
            for secret in core_api.list_namespaced_secret(namespace_val).items:
                name = secret.metadata.name
                namespace = secret.metadata.namespace
                data_length = ("空" if secret.data is None else len(secret.data))
                create_time = secret.metadata.creation_timestamp
                create_time = dt_format(create_time)
                secret = {"name": name, "namespace": namespace, "data_length": data_length, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        secret_list.append(secret)
                else:
                    secret_list.append(secret)
            count = len(secret_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            secret_list = secret_list[start:end]
            code = 0
            msg = "secret获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": secret_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            namespace = del_data.get('namespace')
            core_api.delete_namespaced_secret(namespace=namespace, name=name)
            while True:
                name_list = []
                for secret in core_api.list_namespaced_secret(namespace).items:
                    name_list.append(secret.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)


@login_required
def pvc(request):
    return render(request, "storage/pvc.html")


@login_required
def pvc_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    namespace_val = request.GET.get("namespace")
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        pvc_list = []
        try:
            for pvc in core_api.list_namespaced_persistent_volume_claim(namespace_val).items:
                name = pvc.metadata.name
                namespace = pvc.metadata.namespace
                labels = pvc.metadata.labels
                storage_class_name = pvc.spec.storage_class_name
                access_modes = pvc.spec.access_modes
                capacity = (pvc.status.capacity if pvc.status.capacity is None else pvc.status.capacity["storage"])
                volume_name = pvc.spec.volume_name
                status = pvc.status.phase
                create_time = pvc.metadata.creation_timestamp
                create_time = dt_format(create_time)
                pvc = {"name": name, "namespace": namespace, "lables": labels,
                       "storage_class_name": storage_class_name, "access_modes": access_modes, "capacity": capacity,
                       "volume_name": volume_name, "status": status, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        pvc_list.append(pvc)
                else:
                    pvc_list.append(pvc)
            count = len(pvc_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            pvc_list = pvc_list[start:end]
            code = 0
            msg = "pvc获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": pvc_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            namespace = del_data.get('namespace')
            core_api.delete_namespaced_persistent_volume_claim(namespace=namespace, name=name)
            while True:
                name_list = []
                for pvc in core_api.list_namespaced_persistent_volume_claim(namespace).items:
                    name_list.append(pvc.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)
